/**
 * Created by mars on 2018/5/5.
 */
var Chat = {};
Chat.socket = null;
// 创建一个websocket实例
Chat.connect = (function(host) {
    if ('WebSocket' in window) {
        Chat.socket = new WebSocket(host);
    } else if ('MozWebSocket' in window) {
        Chat.socket = new MozWebSocket(host);
    } else {
        Console.log('Console.log:你的浏览器不支持WebSocket');
        return;
    }
    Chat.socket.onopen = function(){
        Console.log('Console.log:WebSocket链接打开');
        //按下回车键发送消息
        document.getElementById('chat').onkeydown = function(event) {
            if (event.keyCode == 13) {
                Chat.sendMessage();
            }
        };
    };
    Chat.socket.onclose = function () {
        document.getElementById('chat').onkeydown = null;
        Console.log('Console.log:WebSocket前端链接关闭');
    };
    Chat.socket.onmessage = function (message) {
        Console.log(message.data);
    };
});
Chat.initialize = function() {
    //链接地址选择聊天页面的URL
    if (window.location.protocol == 'http:') {
        Chat.connect("ws://" + window.location.host + "/onLineChat/index.jsp");
    } else {
        Chat.connect("wss://" + window.location.host + "/onLineChat/index.jsp");
    }
};
//发送消息函数，后面动态添加了发送好友的唯一ID
Chat.sendMessage = (function() {
    var fid = $("#hidden-fid").val();
    var messageContain = document.getElementById('chat').value;
    var message = messageContain +"-"+fid;
    if(fid==""){
        alert("未选择发送消息的好友！");
        return;
    }else{
        if (messageContain != "") {
            Chat.socket.send(message);
            document.getElementById('chat').value = '';
        }else{
            alert("发送消息不能为空！");
        }
    }
});
var Console = {};
Console.log = (function(message) {
    var console = document.getElementById('console');
    var p = document.createElement('p');
    p.style.wordWrap = 'break-word';
    p.innerHTML = message;
    console.appendChild(p);
    console.scrollTop = console.scrollHeight;
});
//初始化函数
Chat.initialize();
document.addEventListener("DOMContentLoaded", function() {
    var noscripts = document.getElementsByClassName("noscript");
    for (var i = 0; i < noscripts.length; i++) {
        noscripts[i].parentNode.removeChild(noscripts[i]);
    }
}, false);